package com.qk.management.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.course.CourseDTO;
import com.qk.entity.Course;
import com.qk.management.mapper.CourseMapper;
import com.qk.management.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * &#064;author：zzq
 * &#064;createTime：2025/10/09 09:56
 * &#064;description： 
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    // 提取数据校验逻辑为私有方法
    private void validateCourse(Course course) {
        if (course.getName() == null || course.getName().trim().isEmpty()) {
            throw new RuntimeException("课程名称不能为空");
        }
        if (course.getSubject() == null) {
            throw new RuntimeException("课程学科不能为空");
        }
        if (course.getTarget() == null) {
            throw new RuntimeException("适用人群不能为空");
        }
        if (course.getPrice() == null) {
            throw new RuntimeException("课程价格不能为空");
        }
    }

    @Autowired
    private CourseMapper courseMapper;
    //根据name,subject,target模糊分页查询
    @Override
    public PageResult<Course> list(CourseDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Course> list = courseMapper.selectByPage(dto);
        Page<Course> page = (Page<Course>) list;
        return PageResult.<Course>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void addCourse(Course course) {
        //数据校验:name,subject, target为必填
        validateCourse(course);
        //数据补全
        course.setCreateTime(java.time.LocalDateTime.now());
        course.setUpdateTime(java.time.LocalDateTime.now());
        courseMapper.insert(course);
    }

    @Override
    public Course get(Integer id) {
        return courseMapper.selectById(id);
    }

    @Override
    public void update(Course course) {
        //数据校验:name,subject, target为必填
        validateCourse(course);
        //数据补全
        course.setUpdateTime(java.time.LocalDateTime.now());
        courseMapper.updateById(course);
    }

    @Override
    public List<Course> list() {
        return courseMapper.list();
    }

    @Override
    public List<Course> listBySubject(String subject) {
        return courseMapper.listBySubject(subject);
    }
}
